package com.sharemarking.wa.platform.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.SysHttpStatus;
import com.sharemarking.wa.common.eum.OrderStateEum;
import com.sharemarking.wa.common.eum.OrderTypeEum;
import com.sharemarking.wa.common.exception.OrgException;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.eum.OrderOperateTypeEum;
import com.sharemarking.wa.platform.dto.produceWaste.*;
import com.sharemarking.wa.platform.dto.produceWaste.WasteListDto;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.sharemarking.wa.platform.dto.orderCommon.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.*;

/**
 * @author dxy
 */
@Service
public class ProduceWasteService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ProduceWasteMapper produceWasteMapper;
    @Autowired
    private OrgWasteMapper orgWasteMapper;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private OrgMemberMapper orgMemberMapper;

    public ResponseParams<?> chooseWaste() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);
        List<WasteListDto> wasteListDtoList = produceWasteMapper.getChooseWasteList(params);

        return ResponseParams.ok(new Page<>(wasteListDtoList, pageIndex, pageSize, produceWasteMapper.getChooseWasteListTotal(params), wasteListDtoList.size() == pageSize));
    }


    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> addOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        //判断是否认证通过
        Integer isOrgVerify = produceWasteMapper.isOrgVerify(memberId);
        if (isOrgVerify == null || isOrgVerify != 1){
            throw  OrgException.create(ResponseParams.error(UN_P_ORG_VERIFY));
        }

        String wasteList = request.getParameter("wasteList");
        String orgId = request.getParameter("orgId");
        //装货地址
        String loadingAddressId = request.getParameter("loadingAddressId");
        //卸货地址
        String unloadingAddressId = request.getParameter("unloadingAddressId");
        //String driverId = request.getParameter("driverId");
        String isUrgent = request.getParameter("isUrgent");
        String notes = request.getParameter("notes");
        String transferStart = request.getParameter("transferStart");
        String transferEnd = request.getParameter("transferEnd");
        String carRequirement = request.getParameter("carRequirement");
        String transportOrgId = request.getParameter("transportOrgId");
        String carWeight = request.getParameter("carWeight");
        if (StringUtils.isEmpty(carWeight)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("carWeight"));
        }
        if (StringUtils.isEmpty(wasteList)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteList"));
        }
        if (StringUtils.isEmpty(loadingAddressId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("loadingAddressId"));
        }

        if (!StringUtils.isEmpty(orgId) && !StringUtils.isEmpty(unloadingAddressId)) {
            //如果指定了经营商 但出现了卸货地址 不符合业务
            throw RequestException.create(ResponseParams.isDataError("错误的业务"));
        }

        Order parentOrder = new Order();

        if(!StringUtils.isEmpty(isUrgent)){
            parentOrder.setIsUrgent(Integer.valueOf(isUrgent));
        }
        if (!StringUtils.isEmpty(transferStart)){
            parentOrder.setTransferStart(getStringToDate(transferStart));
        }
        if (!StringUtils.isEmpty(transferEnd)){
            parentOrder.setTransferEnd(getStringToDate(transferEnd));
        }
        if(!StringUtils.isEmpty(transportOrgId)){
            parentOrder.setTransportOrgId(Integer.parseInt(transportOrgId));
//            parentOrder.setReceiveOrgMemberId(orgMapper.selectOne(new QueryWrapper<Org>().eq("id",Integer.parseInt(transportOrgId))).getMemberId());
        }
        if (!StringUtils.isEmpty(orgId)) {
            parentOrder.setReceiveOrgId(Integer.valueOf(orgId));
        }

        parentOrder.setCarRequirement(carRequirement);
        parentOrder.setCarWeight(Integer.parseInt(carWeight)*1000);
        parentOrder.setNotes(notes);
        parentOrder.setCreateDate(new Date());
        //找到自己的org_id
        Integer sendOrgId = orgMapper.selectOne(new QueryWrapper<Org>().eq("member_id", memberId)).getId();
        parentOrder.setSendOrgId(sendOrgId);
        parentOrder.setSendOrgMemberId(memberId);
        //设置总订单状态
        parentOrder.setType(0);
        parentOrder.setState(OrderStateEum.UNTREATED.getKey());
        //产生code编号
        String newCode = createNumber();
        parentOrder.setCode(newCode);
        //判断是否重复提交
        if (orderMapper.selectCount(new QueryWrapper<Order>().eq("code", newCode)) == 0) {
            //插入order表
            orderMapper.insert(parentOrder);
        } else {
            throw RequestException.create(ResponseParams.isDataError("请勿重复提交"));
        }


        //装货地址信息插入order_address表 卸货地址(可选)
        Address loadingAddress = addressMapper.selectById(loadingAddressId);
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(loadingAddress, orderAddress);
        orderAddress.setOrderId(parentOrder.getId());
        orderAddress.setType(0);
        orderAddress.setCreateDate(new Date());
        orderAddressMapper.insert(orderAddress);

        if (!StringUtils.isEmpty(unloadingAddressId)) {
            Address unloadingAddress = addressMapper.selectById(unloadingAddressId);
            orderAddress = new OrderAddress();
            BeanUtils.copyProperties(unloadingAddress, orderAddress);
            orderAddress.setOrderId(parentOrder.getId());
            orderAddress.setType(1);
            orderAddress.setCreateDate(new Date());
            orderAddressMapper.insert(orderAddress);
        }

        //json格式的数据转化为list
        List<OrderWasteListDto> orderWasteList = JSONArray.parseArray(wasteList, OrderWasteListDto.class);

        for (int i = 0; i < orderWasteList.size(); i++) {
            OrderDetails orderDetails = new OrderDetails();
            OrgWaste orgWaste = orgWasteMapper.selectById(orderWasteList.get(i).getWasteId());
            orderDetails.setWasteId(orderWasteList.get(i).getWasteId());
            orderDetails.setName(orgWaste.getName());
            orderDetails.setWeight((double) (orderWasteList.get(i).getWeight() * 1000));
            orderDetails.setCreateDate(new Date());
            orderDetails.setOrderId(parentOrder.getId());
            orderDetails.setWasteTypeName(orgWaste.getWasteTypeName());
            //把废品信息插入 order_details表中
            orderDetailMapper.insert(orderDetails);
        }


        //如果自己找到了经营商 计算距离  产生费用
        if (!StringUtils.isEmpty(unloadingAddressId)) {
            //TODO
        }

        //如果选择了经营商 重新新增一条子订单到 order表中
        if (!StringUtils.isEmpty(orgId)) {
            Order childOrder = new Order();
            BeanUtils.copyProperties(parentOrder,childOrder);
            childOrder.setType(1);
            childOrder.setCode(parentOrder.getCode() + "-1");
            childOrder.setCreateDate(new Date());
            childOrder.setState(OrderStateEum.RECEIPT.getKey());
            childOrder.setParentId(parentOrder.getId());
            childOrder.setId(null);
            orderMapper.insert(childOrder);

            //再次插入order_details表
            for (int i = 0; i < orderWasteList.size(); i++) {
                OrderDetails orderDetails = new OrderDetails();
                OrgWaste orgWaste = orgWasteMapper.selectById(orderWasteList.get(i).getWasteId());
                orderDetails.setName(orgWaste.getName());
                orderDetails.setWasteId(orderWasteList.get(i).getWasteId());
                orderDetails.setWeight((orderWasteList.get(i).getWeight() * 1000));
                orderDetails.setCreateDate(new Date());
                orderDetails.setOrderId(childOrder.getId());
                orderDetails.setWasteTypeName(orgWaste.getWasteTypeName());
                orderDetails.setParentOrderId(parentOrder.getId());
                //把废品信息插入 order_details表中
                orderDetailMapper.insert(orderDetails);
            }

            //插入将父订单的地址重新插入
            orderAddress.setOrderId(childOrder.getId());
            orderAddress.setType(0);
            orderAddress.setCreateDate(new Date());
            orderAddressMapper.insert(orderAddress);
        }


        return ResponseParams.ok(null);
    }

    /*
     * 将时间戳转换为时间
     */
    public static Date getStringToDate(String time) throws Exception {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(format.format(new Long(Long.parseLong(time))));
            return date;
        } catch (Exception e) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }
    }


    public static String createNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 2; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> cancelOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
        }

        //判断订单状态
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code).eq("send_org_member_id", memberId));
        if (order == null) {
            throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
        }
        if (!order.getSendOrgMemberId().equals(memberId)) {
            throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
        }

        int state = 0;
        if (order.getType().equals(OrderTypeEum.PARENT_TYPE.getKey())) {
            //总订单 判断是否能取消订单  判断子订单数量
            Integer childOrderCount = orderMapper.selectCount(new QueryWrapper<Order>().eq("parent_id", order.getId()));
            if (childOrderCount == null || childOrderCount != 0) {
                throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
            }
            state = OrderStateEum.CANCEL.getKey();
            //取消订单
            Order updateOrder = new Order();
            updateOrder.setId(order.getId());
            updateOrder.setState(state);
            updateOrder.setUpdateDate(new Date());
            orderMapper.updateById(updateOrder);
        } else if (order.getType().equals(OrderTypeEum.CHILDREN_TYPE.getKey())) {
            //子订单
//            if (order.getState().equals(OrderStateEum.RECEIPT.getKey())) {
//                //待接单
//                state = OrderStateEum.CHILD_ORDER_CANCEL.getKey();
//            } else if (order.getState().equals(OrderStateEum.UNPAID.getKey()) && order.getPayer().equals(1)) {
//                //待付款，且是发布方支付订单
//                if (order.getSendOrgMemberId().equals(memberId)) {
//                    state = OrderStateEum.CHILD_ORDER_CANCEL.getKey();
//                } else {
//                    throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
//                }
//            } else {
//                throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
//            }
//        } else {
//            throw RequestException.create(ResponseParams.error(SysHttpStatus.ORDER_EXCEPTION));
            orderMapper.deleteById(order.getId());
            orderDetailMapper.delete(new QueryWrapper<OrderDetails>().eq("order_id",order.getId()));
            orderAddressMapper.delete(new QueryWrapper<OrderAddress>().eq("order_id",order.getId()));

            String messageStr = "您好，尾号为"+order.getCode().substring(order.getCode().length() - 10)+"的子订单已被"+orgMapper.getOrgNameById(order.getSendOrgId())+"取消";
            jgPushService.pushTag(messageStr,order.getReceiveOrgMemberId());
        }




        return ResponseParams.ok(null);
    }

    public ResponseParams<?> endOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }

        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code));
        if (!order.getSendOrgMemberId().equals(memberId)) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        if (orderMapper.selectCount(new QueryWrapper<Order>().eq("parent_id", order.getId())) == 0) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }


        Order updateOrder = new Order();
        updateOrder.setId(order.getId());
        updateOrder.setState(OrderStateEum.END.getKey());
        updateOrder.setUpdateDate(new Date());
        orderMapper.updateById(updateOrder);

        return ResponseParams.ok(null);
    }

    public ResponseParams<?> chooseOrg() {
        Integer memberId = ss.getCurrentUserId();
        String searchStr = request.getParameter("searchStr");

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);

        if (!StringUtils.isEmpty(searchStr)) {
            params.put("searchStr", searchStr);
        }

        List<OrgListDto> list = produceWasteMapper.getChooseOrgList(params);

        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, produceWasteMapper.getChooseOrgListTotal(params), list.size() == pageSize));
    }

    public ResponseParams<?> chooseDriver() {
        Integer memberId = ss.getCurrentUserId();
        String searchStr = request.getParameter("searchStr");

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        if (!StringUtils.isEmpty(searchStr)) {
            params.put("searchStr", searchStr);
        }

        List<DriverListDto> list = produceWasteMapper.getChooseDriverList(params);

        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, produceWasteMapper.getChooseDriverListTotal(params), list.size() == pageSize));
    }

    public ResponseParams<?> getOrderInfoList() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String wasteId = request.getParameter("wasteId");


        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);


        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }

        if (StringUtils.isEmpty(wasteId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("wasteId"));
        }

        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code",code));
        params.put("orderId", order.getId());
        params.put("wasteId", wasteId);

        //获取子订单列表
        List<Order> list = produceWasteMapper.getOrderInfoList(params);

        List<ChildOrderListDto> childOrderListDto = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i++) {
           ChildOrderListDto c = new ChildOrderListDto();
            c.setCode(list.get(i).getCode());
            c.setId(list.get(i).getId());
            c.setWasteList(produceWasteMapper.getChildOrderList(c.getId(), order.getId()));
            c.setState(list.get(i).getState());
            //判断状态
            List<OrderOperateTypeEum> eumList = new ArrayList<>();
            if (list.get(i).getState().equals(OrderStateEum.RECEIPT.getKey())) {
                //待经营商接单状态：取消订单
                eumList.add(OrderOperateTypeEum.CANCEL);
            } else if (list.get(i).getPayer() != null && list.get(i).getPayer() == 1 && list.get(i).getState().equals(OrderStateEum.UNPAID.getKey())) {
                //代付款状态：取消订单和付款
                eumList.add(OrderOperateTypeEum.CANCEL);
                eumList.add(OrderOperateTypeEum.PAY);
            } else if (list.get(i).getState().equals(OrderStateEum.TRANSPORT_RECEIPT.getKey())) {
                //待运输接单状态：取消订单
                eumList.add(OrderOperateTypeEum.CANCEL);
            }
            c.setOperate(eumList);
            childOrderListDto.add(c);
        }

        return ResponseParams.ok(new Page<>(childOrderListDto, pageIndex, pageSize, produceWasteMapper.getOrderInfoListTotal(params), childOrderListDto.size() == pageSize));

    }
}
